package com.coleloca.androidlongs.collectlocationplication;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.coleloca.androidlongs.collectlocationplication.http.HttpUrlHelper;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.MD5Utils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;

import org.w3c.dom.Text;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class HomeActivity extends AppCompatActivity {
    public int WRITE_COARSE_LOCATION_REQUEST_CODE = 11;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            CommonLoadingUtils.getInstance().closeFunction();

            LogUtils.d("location change ");
            ;
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    locationNumber++;
                    isStart = 3;
                    //可在其中解析amapLocation获取相应内容。
                    switch (locationNumber % 3) {
                        case 0:
                            //mLat2TextView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                            mLat1TextView.setBackgroundColor(Color.parseColor("#50212121"));

                            mLng1TextView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                            //mLng2TextView.setBackgroundColor(Color.parseColor("#50212121"));

                            mStartLocationTextView.setText("实时.");
                            break;
                        case 1:
                            //mLat2TextView.setBackgroundColor(Color.parseColor("#50212121"));
                            mLat1TextView.setBackgroundColor(Color.parseColor("#FFFFFF"));

                            mLng1TextView.setBackgroundColor(Color.parseColor("#50212121"));
                            //mLng2TextView.setBackgroundColor(Color.parseColor("#ffffff"));


                            mStartLocationTextView.setText("实时..");
                            break;
                        case 2:
                            mLng1TextView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                            //mLng2TextView.setBackgroundColor(Color.parseColor("#50212121"));


                            //mLat2TextView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                            mLat1TextView.setBackgroundColor(Color.parseColor("#50212121"));
                            mStartLocationTextView.setText("实时...");
                            break;
                    }

                    //获取纬度
                    mLatitude = amapLocation.getLatitude();
                    mLat1TextView.setText("纬度：" + mLatitude);


                    //获取经度
                    mLongitude = amapLocation.getLongitude();
                    mLng1TextView.setText("经度：" + mLongitude);


                    mAddress = amapLocation.getAddress();
                    LogUtils.d(" ----  " + mAddress);
                    mCurrentAdressTextView.setText(mAddress);


                    mAltitude = amapLocation.getAltitude();
                    mAltitude1TextView.setText("海拔：" + mAltitude);


                } else {
                    isStart = 4;
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private TextView mStartLocationTextView;
    private TextView mLat2TextView;
    private TextView mLat1TextView;
    private TextView mLng1TextView;
    private TextView mLng2TextView;
    private TextView mCurrentAdressTextView;
    private TextView mAltitude2TextView;
    private TextView mAltitude1TextView;
    private EditText mCurrentAdress2TextView;
    private TextView mUserLocationTextView;
    private double mLatitude = 0;
    private double mLongitude = 0;
    private String mAddress = "--";
    private double mAltitude = 0;
    public Context mContext;
    private TextView mAddLocationTextView;
    private SchoolModel mSchoolModel;
    private TextView mCurrentSchoolTextView;
    //教室名称
    private EditText mBuildStayEditText;
    private EditText mBuildNameEditText;
    private RecyclerView mSchoolBuildRecyclerView;
    private TextView mUpdateSchoolBuildTextView;
    private TextView mCancleAlertTextVeiw;
    private TextView mDeleteTextView;
    private TextView mAlertShowBuildNameTextView;
    private TextView mAlertShowBuildStayNameTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        Intent intent = getIntent();
        mSchoolModel = (SchoolModel) intent.getSerializableExtra("schoolMolde");


        mContext = this;

        mStartLocationTextView = findViewById(R.id.tv_start_location);

        mLat1TextView = findViewById(R.id.tv_lat_1);
        mLat2TextView = findViewById(R.id.tv_lat_2);

        mLng1TextView = findViewById(R.id.tv_lon_1);
        mLng2TextView = findViewById(R.id.tv_lon_2);

        mCurrentAdressTextView = findViewById(R.id.tv_current_adrress);
        mCurrentAdress2TextView = findViewById(R.id.tv_current_adrress2);


        mAltitude1TextView = findViewById(R.id.tv_altitude_1);
        mAltitude2TextView = findViewById(R.id.tv_altitude_2);

        mUserLocationTextView = findViewById(R.id.tv_use_location);

        mAddLocationTextView = findViewById(R.id.tv_add_location_infor);

        mCurrentSchoolTextView = findViewById(R.id.tv_current_school_name);

        mBuildStayEditText = findViewById(R.id.tv_current_adrress_build_stay);

        mBuildNameEditText = findViewById(R.id.tv_current_adrress_build_name);

        mSchoolBuildRecyclerView = findViewById(R.id.rv_school_build_list);


        mUpdateSchoolBuildTextView = findViewById(R.id.tv_update_school_list);

        mAlertShowBuildNameTextView = findViewById(R.id.tv_show_alert_build_name);
        mAlertShowBuildNameTextView.setVisibility(View.GONE);
        mAlertShowBuildStayNameTextView = findViewById(R.id.tv_show_alert_build_stay_name);
        mAlertShowBuildStayNameTextView.setVisibility(View.GONE);


        mCancleAlertTextVeiw = findViewById(R.id.tv_canle_location_infor);
        mCancleAlertTextVeiw.setVisibility(View.GONE);
        mDeleteTextView = findViewById(R.id.tv_delete_location_infor);
        mDeleteTextView.setVisibility(View.GONE);
        if (mSchoolModel != null) {
            mCurrentSchoolTextView.setText("当前学校：" + mSchoolModel.getName());
        } else {
            mCurrentSchoolTextView.setText("当前学校：" + "暂无学校信息");
        }

        //SDK在Android 6.0下需要进行运行检测的权限如下：

        /**
         *  Manifest.permission.ACCESS_COARSE_LOCATION,
         Manifest.permission.ACCESS_FINE_LOCATION,
         Manifest.permission.WRITE_EXTERNAL_STORAGE,
         Manifest.permission.READ_EXTERNAL_STORAGE,
         Manifest.permission.READ_PHONE_STATE
         */


        //这里以ACCESS_COARSE_LOCATION为例
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
                    WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
        }

        inintMapFunction();

        mStartLocationTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {
                if (mLocationClient != null && (isStart == 0 || isStart == 2)) {
                    isStart = 1;
                    //启动定位
                    mLocationClient.startLocation();
                    mStartLocationTextView.setText("正在初始化");

                    CommonLoadingUtils.getInstance().showLoading(mStartLocationTextView);
                } else if (isStart == 4) {
                    ToastUtils.show("初始化定位功能失败，请重新进入", HomeActivity.this);
                } else if (isStart == 3) {
                    //停止
                    mStartLocationTextView.setText("开始");
                    mLat1TextView.setText("纬度：--");
                    mLat2TextView.setText("--");

                    mLng1TextView.setText("经度：--");
                    mLng2TextView.setText("--");

                    mAltitude1TextView.setText("海拔：--");
                    mAltitude2TextView.setText("--");
                    mLocationClient.stopLocation();

                    mAddress = "--";
                } else {
                    ToastUtils.show("正在初始化定位功能", HomeActivity.this);
                }

            }
        });
        mUserLocationTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {
                mLat2TextView.setText("" + mLatitude);
                mLng2TextView.setText("" + mLongitude);
                mCurrentAdress2TextView.setText(mAddress);
                mAltitude2TextView.setText("" + mAltitude);
            }
        });

        mAddLocationTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {
                if (mBuildModel != null) {
                    alertLocationFunction();
                } else {
                    addLocationFunction();
                }

            }
        });
        mUpdateSchoolBuildTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {
                updateLocationListFunction();
            }
        });

        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                updateLocationListFunction();
            }
        }, 1400);

        mCancleAlertTextVeiw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {

                mBuildModel = null;

                mAlertShowBuildNameTextView.setText("" );
                mAlertShowBuildStayNameTextView.setText("" );

                mAlertShowBuildNameTextView.setVisibility(View.GONE);
                mAlertShowBuildStayNameTextView.setVisibility(View.GONE);

                mBuildNameEditText.setVisibility(View.VISIBLE);
                mBuildStayEditText.setVisibility(View.VISIBLE);


                mCancleAlertTextVeiw.setVisibility(View.GONE);
                mDeleteTextView.setVisibility(View.GONE);
                mAddLocationTextView.setText("添加");
            }
        });

        mDeleteTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View lView) {
                deleteLocationFunction();
            }
        });
    }

    private void deleteLocationFunction() {

        String addUrl = HttpUrlHelper.deleteLocationListUrl;

        ConcurrentHashMap<String, String> kepMap = new ConcurrentHashMap<>();


        kepMap.put("uuid", mBuildModel.getUuid());

        CommonLoadingUtils.getInstance().showLoading(mAddLocationTextView);

        OkhttpCommonClient.sentPostRequest(addUrl, kepMap, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("request success ");
                ToastUtils.show("删除成功", mContext);
                CommonLoadingUtils.getInstance().closeFunction();
                updateLocationListFunction();

                mBuildModel = null;

                mAlertShowBuildNameTextView.setText("" );
                mAlertShowBuildStayNameTextView.setText("" );

                mAlertShowBuildNameTextView.setVisibility(View.GONE);
                mAlertShowBuildStayNameTextView.setVisibility(View.GONE);

                mBuildNameEditText.setVisibility(View.VISIBLE);
                mBuildStayEditText.setVisibility(View.VISIBLE);


                mCancleAlertTextVeiw.setVisibility(View.GONE);
                mDeleteTextView.setVisibility(View.GONE);
                mAddLocationTextView.setText("添加");
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("删除失败，网络异常", mContext);

                CommonLoadingUtils.getInstance().closeFunction();
            }
        });
    }

    private void alertLocationFunction() {
        if (mLatitude == 0) {
            ToastUtils.show("请先获取位置信息", mContext);
            return;
        }

        String buildName = mBuildNameEditText.getText().toString();
        if (buildName == null || buildName.equals("")) {
            ToastUtils.show("请先填写建筑位置信息", mContext);
            return;
        }

        String stayName = mBuildStayEditText.getText().toString();
        if (stayName == null || stayName.equals("")) {
            ToastUtils.show("请先填写教室或者宿舍位置信息", mContext);
            return;
        }

        String addUrl = HttpUrlHelper.addLocationUrl;

        ConcurrentHashMap<String, String> kepMap = new ConcurrentHashMap<>();


        kepMap.put("uuid", mBuildModel.getUuid());
        kepMap.put("buildname", buildName);
        kepMap.put("classroom", stayName);
        kepMap.put("univerid", mSchoolModel.getId() + "");


        //经度
        kepMap.put("lati", mLatitude + "");
        //维度
        kepMap.put("lon", mLongitude + "");
        //海拔
        kepMap.put("height", mAltitude + "");

        CommonLoadingUtils.getInstance().showLoading(mAddLocationTextView);

        OkhttpCommonClient.sentPostRequest(addUrl, kepMap, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("request success ");
                ToastUtils.show("修改成功", mContext);
                CommonLoadingUtils.getInstance().closeFunction();
                updateLocationListFunction();

                mBuildModel = null;

                mAlertShowBuildNameTextView.setText("" );
                mAlertShowBuildStayNameTextView.setText("" );

                mAlertShowBuildNameTextView.setVisibility(View.GONE);
                mAlertShowBuildStayNameTextView.setVisibility(View.GONE);

                mBuildNameEditText.setVisibility(View.VISIBLE);
                mBuildStayEditText.setVisibility(View.VISIBLE);


                mCancleAlertTextVeiw.setVisibility(View.GONE);
                mDeleteTextView.setVisibility(View.GONE);
                mAddLocationTextView.setText("添加");
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("修改失败，网络异常", mContext);

                CommonLoadingUtils.getInstance().closeFunction();
            }
        });
    }

    private void addLocationFunction() {

        if (mAddress == null || mAddress.equals("--")) {
            ToastUtils.show("请先获取位置信息", mContext);
            return;
        }

        if (mSchoolModel == null) {
            ToastUtils.show("学校信息异常", mContext);
            return;
        }

        String buildName = mBuildNameEditText.getText().toString();
        if (buildName == null || buildName.equals("")) {
            ToastUtils.show("请先填写建筑位置信息", mContext);
            return;
        }

        String stayName = mBuildStayEditText.getText().toString();
        if (stayName == null || stayName.equals("")) {
            ToastUtils.show("请先填写教室或者宿舍位置信息", mContext);
            return;
        }
        String addUrl = HttpUrlHelper.addLocationUrl;

        ConcurrentHashMap<String, String> kepMap = new ConcurrentHashMap<>();


        kepMap.put("buildname", buildName);
        kepMap.put("classroom", stayName);
        kepMap.put("univerid", mSchoolModel.getId() + "");


        //经度
        kepMap.put("lati", mLatitude + "");
        //维度
        kepMap.put("lon", mLongitude + "");
        //海拔
        kepMap.put("height", mAltitude + "");

        CommonLoadingUtils.getInstance().showLoading(mAddLocationTextView);

        OkhttpCommonClient.sentPostRequest(addUrl, kepMap, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("request success ");
                ToastUtils.show("添加成功", mContext);
                CommonLoadingUtils.getInstance().closeFunction();
                updateLocationListFunction();
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("添加失败，网络异常", mContext);

                CommonLoadingUtils.getInstance().closeFunction();
            }
        });
    }

    private void updateLocationListFunction() {
        String addUrl = HttpUrlHelper.getLocationListUrl;

        ConcurrentHashMap<String, String> kepMap = new ConcurrentHashMap<>();
        CommonLoadingUtils.getInstance().showLoading(mAddLocationTextView);

        OkhttpCommonClient.sentGetRequest(addUrl, kepMap, new OkhttpCommonCallBack(BuildModel.class) {
            @Override
            public void onSuccess(Object obj) {
                LogUtils.d("get build name request success ");
                List<BuildModel> buildModels = (List<BuildModel>) obj;
                setRecyclerviewFunction(buildModels);
                CommonLoadingUtils.getInstance().closeFunction();
            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("更新列表失败，网络异常", mContext);
                CommonLoadingUtils.getInstance().closeFunction();
                ToastUtils.show("更新数据失败", mContext);
            }
        });
    }

    private HomeActivity.SchoolListAdapter mSchoolListAdapter;

    private void setRecyclerviewFunction(List<BuildModel> lBuildModels) {

        if (mSchoolListAdapter == null) {
            mSchoolListAdapter = new HomeActivity.SchoolListAdapter(lBuildModels);
            mSchoolBuildRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            mSchoolBuildRecyclerView.setAdapter(mSchoolListAdapter);
        } else {
            mSchoolListAdapter.updateListDate(lBuildModels);
            mSchoolListAdapter.notifyDataSetChanged();
        }
    }


    public class SchoolListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        public List<BuildModel> mSchoolModelList;

        public SchoolListAdapter(List<BuildModel> lSchoolModelList) {
            mSchoolModelList = lSchoolModelList;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new HomeActivity.SchoolViewHolder(View.inflate(mContext, R.layout.item_school_infor, null));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            BuildModel schoolModel = mSchoolModelList.get(position);
            HomeActivity.SchoolViewHolder schoolViewHolder = (HomeActivity.SchoolViewHolder) holder;
            schoolViewHolder.setDatas(schoolModel, position);
        }

        @Override
        public int getItemCount() {
            return mSchoolModelList == null ? 0 : mSchoolModelList.size();
        }

        public void updateListDate(List<BuildModel> lSchoolModelList) {
            mSchoolModelList = lSchoolModelList;
        }
    }

    //修改的模型
    public BuildModel mBuildModel;

    public class SchoolViewHolder extends RecyclerView.ViewHolder {

        private final TextView mSchoolNameTextView;

        public SchoolViewHolder(View itemView) {
            super(itemView);
            mSchoolNameTextView = itemView.findViewById(R.id.tv_school_name);
        }

        public void setDatas(final BuildModel lSchoolModel, int lPosition) {
            mSchoolNameTextView.setText("" + lSchoolModel.getName() + " " + lSchoolModel.getBuildname() + " " + lSchoolModel.getClassroom());

            mSchoolNameTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View lView) {

                    mAlertShowBuildNameTextView.setText("" + lSchoolModel.getBuildname());
                    mAlertShowBuildStayNameTextView.setText("" + lSchoolModel.getClassroom());

                    mAlertShowBuildNameTextView.setVisibility(View.VISIBLE);
                    mAlertShowBuildStayNameTextView.setVisibility(View.VISIBLE);

                    mBuildNameEditText.setVisibility(View.GONE);
                    mBuildStayEditText.setVisibility(View.GONE);

                    mBuildModel = lSchoolModel;

                    mCancleAlertTextVeiw.setVisibility(View.VISIBLE);
                    mDeleteTextView.setVisibility(View.VISIBLE);
                    mAddLocationTextView.setText("修改");
                }
            });
        }
    }

    public int isStart = 0;
    public int locationNumber = 0;

    private void inintMapFunction() {


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption.setInterval(1000);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //可在此继续其他操作。

        try {
            inintMapFunction();
        } catch (Exception lE) {
            lE.printStackTrace();
        }

    }
}
